package com.zc.shiro;


import com.zc.dao.UsersMapper;
import com.zc.entity.Path;
import com.zc.entity.Test;
import com.zc.entity.Users;
import com.zc.service.JedisClient;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态生成nav
 */
public class MyRealmByDynamic extends AuthorizingRealm {

    @Resource
    private UsersMapper userDao;

    @Resource
    private JedisClient jedis;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //认证并授权
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) arg0;
        String username = token.getUsername();
//		char[] password = token.getPassword();
        Users userInfo = userDao.selectByName(username);
        if (userInfo == null) {
            return null;
        }
        String roleID = userInfo.getRoleId();

        List<Path> list;
        if ("1".equals(roleID)) {
            list = userDao.selectPathAll();
        } else {
            list = userDao.selectPathByrole(roleID);
        }

        //拼接动态nav
        String nav = splitNav(list);
        //将key:username,value:nav存放到redis
        String redisKey = userInfo.getUsername() + "nav";
        jedis.set(redisKey, nav);
        //设置失效时间
        jedis.expire(redisKey, 3 * 60 * 60);

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userInfo, userInfo.getPassword(), this.getClass().getName());
        return info;
    }

    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        //授权信息对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Users userInfo = (Users) arg0.getPrimaryPrincipal();
        String roleID = userInfo.getRoleId();
//        List<Path> list;
//        if ("0".equals(roleID)) {
//            list = userDao.selectPathAll();
//        } else {
//            list = userDao.selectPathByrole(roleID);
//        }
//
//        //拼接动态nav
//        String nav = splitNav(list);
//        //将key:username,value:nav存放到redis
//        String redisKey = userInfo.getUsername()+"nav";
//        jedis.set(redisKey,nav);
//        //设置失效时间
//        jedis.expire(redisKey,3*60*60);
//        logger.debug("role,permission,{},{}", list);
        return info;
    }

    private String splitNav(List<Path> list) {
        String nav = "";
        Map<Integer, StringBuffer> navMap = new LinkedHashMap<>();
        //初始化map,拼接根目录
        initNavMap(navMap, list);
        //拼接sonleaf
        splitSonleaf(navMap, list);
        //最后做完整拼接
        nav = splitComplete(navMap);

        return nav;
    }

    private String splitComplete(Map<Integer, StringBuffer> navMap) {
        StringBuilder sb = new StringBuilder();
        String end = "</ul></li>";
        for (Map.Entry<Integer, StringBuffer> map : navMap.entrySet()) {
            String content = map.getValue().toString();
            if (content.startsWith("&&@@")) {
                sb.append(content.replace("&&@@", "")).append(end);
            } else {
                sb.append(content);
            }
        }
        return sb.toString();
    }

    private void splitSonleaf(Map<Integer, StringBuffer> navMap, List<Path> list) {
        for (Path path : list) {
            //判断是不是根目录
            if (path.getRootLeaf() == 0) {
                continue;
            }
            int fatherLeaf = path.getFatherLeaf();
            String pathId = getpathID(path.getPathName());
            String content = " <li id='" + pathId + "'>\n" +
                    "              <a class='submenu' href='" + path.getPathName() + "'><i class='icon-file-alt'></i>\n" +
                    "              <span class='hidden-tablet'>" + path.getRemark() + "</span>\n" +
                    "              </a>\n" +
                    "              </li>";
            navMap.get(fatherLeaf).append(content);
        }
    }

    private String getpathID(String pathname) {
        //字符串类似"html/twoProduce.html";
        String pathID = "";
        try {
            int index = pathname.lastIndexOf("/");
            int lastindex = pathname.lastIndexOf(".");
            pathID = pathname.substring(index + 1, lastindex);
        } catch (StringIndexOutOfBoundsException e) {
            return pathname;
        }
        return pathID;
    }

    private void initNavMap(Map<Integer, StringBuffer> navMap, List<Path> list) {
        //将key:根目录和value:stringbuffer初始化map
        for (Path path : list) {
            StringBuffer sb = null;
            Integer rootID = path.getId();
            Integer rootLeaf = path.getRootLeaf();
            if (0 == rootLeaf) {
                sb = new StringBuffer();
                String content = "";
                String pathId = getpathID(path.getPathName());
                if (path.getSonLeaf() == 0) {
                    content = "&&@@<li id = '" + pathId + "'>\n" +
                            "         <a class='dropmenu' href='javascript:void(0);' onclick='displayColumn(this);'><i class='icon-folder-close-alt'></i>\n" +
                            "         <span class='hidden-tablet'>" + path.getRemark() + "</span>\n" +
                            "         </a>\n" +
                            "         <ul style='display:none;'>";
                } else {
                    content = "<li id='" + pathId + "'><a href='" + path.getPathName() + "'><i class='icon-bar-chart'></i><span class='hidden-tablet'>" + path.getRemark() + "</span> </a>\n" +
                            "                    </li>";
                }
                sb.append(content);
                navMap.put(rootID, sb);
            }
        }

    }

//    public static void main(String[] args) {
//        MyRealmByDynamic s =new MyRealmByDynamic();
//        System.out.println(s.getpathID("html/twoProduce.html"));
//    }

//    public static void main(String[] args) {
//        String ss ="@@$$aksdfsahjkfhkjashjfkhsajkhfjsafhkj";
//        System.out.println(ss.startsWith("@@$$"));
//    }
}
